﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Management;

namespace WINADM.Server.WMI
{
   public class Win32ProcessHelper : IWin32ProcessHelper
    {
       ILog _logger;
       public Win32ProcessHelper(ILog logger)
        {
            _logger = logger;
        }
       public IList<Win32Process> GetAllProcesses()
        {
            IList<Win32Process> win32Processes = new List<Win32Process>();

            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(WMIConstants.WMIRootNamespace, WMIConstants.WMIQuery_AllProcessQuery);

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    win32Processes.Add(new Win32Process(queryObj));

                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error occured while fetching process information", ex);
            }
            return win32Processes;
        }

       public bool Terminate(string win32ProcessesName)
       {
           return false;
       }


       private bool InvokeWMIMethod(string win32ProcessName, string methodName)
       {
           try
           {
               ManagementObject classInstance =
                   new ManagementObject(WMIConstants.WMIRootNamespace, String.Format(WMIConstants.WMIQuery_SingleServiceQuery, win32ProcessName),
                   null);

               // Execute the method and obtain the return values.
               if (classInstance == null)
                   throw new WMIOperationException(String.Format(WMIConstants.WMIMethod_ServiceInstance_Null_Message, win32ProcessName));

               ManagementBaseObject outParams = classInstance.InvokeMethod(methodName, null, null);

               UInt32 returnVal = Convert.ToUInt32(outParams[WMIConstants.WMIMethodReturnValue]);

               if (returnVal == 0)
                   return true;
               else
                   throw new WMIOperationException(String.Format(WMIConstants.WMIMethod_InvokeMethod_UnSuccessfull_Message, methodName,
                       win32ProcessName, DecodeMethodReturnVal(returnVal)));
           }
           catch (Exception ex)
           {
               _logger.Error(String.Format(WMIConstants.WMIMethod_InvokeMethod_Exception_Message, methodName), ex);
               throw new WMIOperationException(String.Format(WMIConstants.WMIMethod_InvokeMethod_Exception_Message,
                   methodName) + "::" + ex.Message, ex);
           }
       }
       private string DecodeMethodReturnVal(UInt32 returval)
       {
           return String.Empty;
       }
   
    }
}
